<template>
  <a-layout id="mainLayout">
    <a-layout-sider class="sidebar">
      <a-col>
        <div class="userDiv">
          <b style="color: white">在线用户({{ userList.length }}人)</b>
        </div>
        <div class="userDiv" v-for="(user, index) in userList" :key="index">
          <a-space>
            <icon-user style="color: white" />
            <span style="color: white">{{ user }}</span>
          </a-space>
        </div>
      </a-col>
    </a-layout-sider>
    <a-layout id="mainContent">
      <a-col id="recordCol">
        <div class="chatDiv">
          <span style="font-weight: bold">群聊记录</span>
        </div>
        <div
          class="chatDiv"
          v-for="(record, index) in chatRecords"
          :key="index"
        >
          <div style="width: 60%">
            <a-comment
              style="text-align: left"
              :author="record.username"
              :content="record.content"
              :datetime="moment(record.time).format('YYYY-MM-DD HH:mm:ss')"
            >
              <template #avatar>
                <a-avatar style="background-color: #3370ff">
                  {{ record.username.at(0).toUpperCase() }}
                </a-avatar>
              </template>
            </a-comment>
          </div>
        </div>
        <div id="bottomTarget" style="height: 180px"></div>
      </a-col>
      <div class="footer">
        <a-input
          v-model="message"
          class="input"
          placeholder="输入消息"
          @press-enter="handleSend"
          allow-clear
        >
          <template #suffix>
            <a-button
              type="secondary"
              style="background-color: transparent"
              @click="handleSend"
            >
              <template #icon>
                <icon-send />
              </template>
            </a-button>
          </template>
        </a-input>
      </div>
    </a-layout>
  </a-layout>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import axios from "axios";
import { Modal } from "@arco-design/web-vue";
import moment from "moment";
import { useStore } from "vuex";
import { useRouter } from "vue-router";

const store = useStore();
let currentUser = store.state.user.currentUser;
const router = useRouter();

const userList = reactive([]);
const chatRecords = ref([]);
const message = ref("");

onMounted(async () => {
  if (currentUser.username === "未登录") {
    await store.dispatch("user/getLoginUser");
    currentUser = store.state.user.currentUser;
  }
  if (currentUser.username === "未登录") {
    await router.push({
      path: "/login",
    });
  } else {
    initWebSocket();
    await loadUserList();
    await loadChatRecords();
  }
});

const loadUserList = async () => {
  const res = await axios({
    method: "get",
    url: "http://localhost:8081/user/all",
  });
  if (res.data.code === 0) {
    userList.push(...res.data.data);
  } else {
    Modal.error({
      title: "加载失败",
      content: "错误信息：" + res.data.message,
      bodyStyle: {
        textAlign: "center",
      },
    });
  }
};

const loadChatRecords = async () => {
  const res = await axios({
    method: "get",
    url: "http://localhost:8081/chat/get",
  });
  if (res.data.code === 0) {
    chatRecords.value = res.data.data;
    const mainContent = document.getElementById("mainContent");
    setTimeout(() => {
      mainContent.scrollTo({ top: mainContent.scrollHeight, left: 100 });
    });
  } else {
    Modal.error({
      title: "加载失败",
      content: "错误信息：" + res.data.message,
      bodyStyle: {
        textAlign: "center",
      },
    });
  }
};

const handleSend = async () => {
  const res = await axios({
    method: "get",
    url: "http://localhost:8081/chat/send",
    params: {
      content: message.value,
    },
  });
  if (res.data.code === 0) {
    message.value = "";
  } else {
    Modal.error({
      title: "发送失败",
      content: "错误信息：" + res.data.message,
      bodyStyle: {
        textAlign: "center",
      },
    });
  }
};

let websocket;

const initWebSocket = () => {
  const userId = currentUser.username;
  const url = "ws://localhost:8081/websocket/" + userId;
  websocket = new WebSocket(url);
  websocket.onmessage = websocketOnMessage;
};

const websocketOnMessage = (e) => {
  let data = JSON.parse(e.data);
  if (data?.user) {
    if (!userList.includes(data.user)) {
      userList.push(data.user);
    }
  }
  if (data?.message) {
    chatRecords.value.push(data.message);
    const mainContent = document.getElementById("mainContent");
    setTimeout(() => {
      mainContent.scrollTo({ top: mainContent.scrollHeight, left: 100 });
    });
  }
};
</script>

<style>
#mainLayout {
  height: 100vh;
  width: 100%;
}

#mainLayout .userDiv {
  padding: 12px 20px;
  border-bottom: 2px solid rgb(0, 170, 255);
}

#mainLayout .sidebar {
  background-color: rgb(0, 170, 255);
  min-width: 240px;
}

#mainLayout .chatDiv {
  display: flex;
  justify-content: center;
  width: 100%;
  padding: 32px 0;
  border-bottom: 1px solid var(--color-neutral-3);
}

#mainLayout .footer {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  position: absolute;
  bottom: 0;
  left: 240px;
  right: 0;
  height: 180px;
  background: linear-gradient(to top, var(--color-neutral-2), transparent);
}

#mainLayout .input {
  width: 60%;
  height: 50px;
  margin-bottom: 32px;
  border: 1px solid var(--color-neutral-4);
  background-color: white;
  border-radius: 16px;
}
</style>
